package com.bms.admin.config;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.bms.admin.base.log.entity.Log;
import com.bms.admin.base.log.service.ILogService;
import com.bms.auth.SubjectUtil;
import com.bms.common.base.common.util.HttpContextUtils;
import com.bms.common.base.common.util.IPUtils;
import com.bms.common.base.common.util.JsonUtil;
import com.feilong.core.Validator;
import com.feilong.core.date.DateExtensionUtil;

import io.swagger.annotations.ApiOperation;

@Aspect
@Component
public class WebLogAspect {

	private static Logger log = LoggerFactory.getLogger(WebLogAspect.class);

	@Autowired
	private ILogService logService;

	@Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
	public void logPointCut() {
	}

	@Pointcut("execution(* com.bms.admin.base.index.web.LoginController.*(..))")
	public void loginPointCut() {
	}

	@Around("logPointCut() && !loginPointCut()")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		MethodSignature signature = (MethodSignature) pjp.getSignature();
		Method method = signature.getMethod();
		HttpServletRequest request = attributes.getRequest();
		ApiOperation operation = method.getAnnotation(ApiOperation.class);
		log.info("请求方法 :{} " , operation.value());
		log.info("地址 : {}", request.getRequestURL().toString());
		log.info("参数 : {}" , Arrays.toString(pjp.getArgs()));
		Date beginDate = new Date();
		Object ob = pjp.proceed();
		log.info("耗时 : {}" , DateExtensionUtil.formatDuration(beginDate));
		log.info("==================================================");
		saveSysLog(pjp, DateExtensionUtil.formatDuration(beginDate));
		return ob;
	}

	private void saveSysLog(ProceedingJoinPoint joinPoint, String time) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

		Log sysLog = new Log();
		ApiOperation syslog = method.getAnnotation(ApiOperation.class);
		if(syslog != null){
			//注解上的描述
			sysLog.setOperation(syslog.value());
		}

		//请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		sysLog.setMethod(className + "." + methodName + "()");

		//请求的参数
		Object[] args = joinPoint.getArgs();
		StringBuilder params = new StringBuilder();
		for(Object arg : args){
			if(method.getParameterTypes()[0].getName().equalsIgnoreCase("org.springframework.web.multipart.MultipartFile")){
				continue;
			}
			if(Validator.isNotNullOrEmpty(arg)){
				params.append(JsonUtil.getJsonFromObject(arg));
				params.append("&");
			}
			
		}
		sysLog.setParams(StringUtils.isBlank(params.toString()) ? null :params.toString().substring(0, params.toString().length()-1));
		//获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		//设置IP地址
		sysLog.setIp(IPUtils.getIpAddr(request));

		//用户名
		String token = SubjectUtil.getInstance().getRequestToken(request);
		if(Validator.isNotNullOrEmpty(token)){
			Map<String,Object> clailms = SubjectUtil.getInstance().getTokenParams(token);
			sysLog.setUsername(clailms.get("username").toString());
		}
		sysLog.setTime(time);
		sysLog.setCreateTime(new Date());
		//保存系统日志
		logService.insert(sysLog);
	}
}
